import { useModel } from '@umijs/max';
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import styles from './index.less';

import { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import { useEffect, useState } from 'react';
// const isDev = process.env.NODE_ENV === 'development';

interface Props {
  label: string;
  value: string;
  placeholder?: string;
  onChange: (value: string) => void;
}
type InsertFnType = (url: string) => void;

export default function MyEditor(props: Props) {
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const { label, value, placeholder, onChange} = props;
  const [editor, setEditor] = useState<IDomEditor | null>(null);
  // 编辑器内容
  // const [html, setHtml] = useState('');

  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {};

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    placeholder: placeholder,
    MENU_CONF: {
      uploadImage: {
        server: `/apiupload/admin/z_file/uploadE`,
        fieldName: 'file',
        headers: {
          Token: currentUser?.token,
        },
        // 自定义插入图片
        customInsert(res: any, insertFn: InsertFnType) {
          console.log(res);
          if (res.success) {
            insertFn(`${res.data.src}`);
          }
        },
      },
    },
  };

  // 及时销毁 editor ，重要！
  useEffect(() => {
    // setHtml(value);
    return () => {
      if (editor === null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  return (
    <div className={styles.MyEditor}>
      <div className={styles.label}>
        <span>{label}</span>
      </div>
      <div  style={{ border: '1px solid #ccc', zIndex: 100 }}>
        <Toolbar
          editor={editor}
          defaultConfig={toolbarConfig}
          mode="simple"
          style={{ borderBottom: '1px solid #ccc' }}
        />
        <Editor
          defaultConfig={editorConfig}
          value={value}
          onCreated={setEditor}
          onChange={(editor) => {
            // setHtml(editor.getHtml());
            onChange(editor.getHtml());
          }}
          mode="simple"
          style={{ height: '400px', overflowY: 'hidden' }}
        />
      </div>
    </div>
  );
}
